<!--
 * @Description: 表格组件
-->
<template>
  <div class="_excel cpt_round_card">
    <ehl-form class="confirm" :options="confirm.options" :data="confirm.data" />
    <div id="luckysheet" class="_excel_box"></div>
    <i class="_export_excel el-icon-camera-solid" v-if="exportBtn" @click="camera"></i>
    <i
      class="_add_excel el-icon-circle-plus-outline"
      v-if="importBtn"
      @click="$refs.selectFile.click()"
    ></i>
    <input
      ref="selectFile"
      :style="{ weight: 0, height: 0 }"
      type="file"
      accept=".csv,.xlsx,.xls"
    />
  </div>
</template>
<script>
  import ehlForm from '@/common'
  import { importJs, importCss } from '@/common/utils/api.js'
  import LuckyExcel from 'luckyexcel'
  export default {
    props: {
      //包含sheet中的所有数据，包括表头
      value: {
        type: Array,
        default: () => [],
      },
      //当前sheet的所有配置，合并，保护区域之类的
      config: {
        type: Object,
        default: () => ({}),
      },
      //显示导入按钮
      importBtn: {
        type: Boolean,
        default: () => true,
      },
      //显示导出按钮
      exportBtn: {
        type: Boolean,
        default: () => true,
      },
      //显示导出按钮
      readOnly: {
        type: Boolean,
        default: () => false,
      },
      defaultConfig: {
        type: Object,
        default: () => ({
          container: 'luckysheet', // 设定DOM容器的id
          title: 'Luckysheet Demo', // 设定表格名称
          lang: 'zh', // 设定表格语言
          plugins: ['chart'],
          allowEdit: false,
          showinfobar: false, //信息栏
          sheetFormulaBar: true, //是否显示公式栏
          showtoolbar: false, //自定义工具栏
          showsheetbar: false, //自定义底部sheet页
          // showstatisticBar: false,//自定义计数栏
          showstatisticBarConfig: {
            count: false, // 计数栏
            view: false, // 打印视图
            // zoom: false, // 缩放
          },
          // forceCalculation: true, //刷新公式
          enableAddRow: false, //允许添加行
          enableAddBackTop: false, //允许回到顶部
          // rowHeaderWidth: 0, //行标题区域的宽度，如果设置为0，则表示隐藏行标题
          // columnHeaderHeight: 0, //列标题区域的高度，如果设置为0，则表示隐藏列标题
          cellRightClickConfig: {
            //编辑右键菜单
            copy: false, // 复制
            copyAs: false, // 复制为
            paste: false, // 粘贴
            insertRow: false, // 插入行
            insertColumn: false, // 插入列
            deleteRow: false, // 删除选中行
            deleteColumn: false, // 删除选中列
            deleteCell: false, // 删除单元格
            hideRow: false, // 隐藏选中行和显示选中行
            hideColumn: false, // 隐藏选中列和显示选中列
            rowHeight: false, // 行高
            columnWidth: false, // 列宽
            clear: false, // 清除内容
            matrix: false, // 矩阵操作选区
            sort: false, // 排序选区
            filter: false, // 筛选选区
            chart: false, // 图表生成
            image: false, // 插入图片
            link: false, // 插入链接
            data: false, // 数据验证
            cellFormat: false, // 设置单元格格式
          },
          hook: {},
          data: [
            {
              // name: 'Cell', //工作表名称
              // color: '', //工作表颜色
              // index: 0, //工作表索引
              // status: 1, //激活状态
              // order: 0, //工作表的下标
              // hide: 0, //是否隐藏
              // row: 30, //行数
              // column: 25, //列数
              // defaultRowHeight: 19, //自定义行高
              // defaultColWidth: 73, //自定义列宽
              celldata: [], //初始化使用的单元格数据
              config: {
                // merge: {}, //合并单元格
                // rowlen: {}, //表格行高
                // columnlen: {}, //表格列宽
                // rowhidden: {}, //隐藏行
                // colhidden: {}, //隐藏列
                // borderInfo: {}, //边框
                // authority: {}, //工作表保护
              },
              // scrollLeft: 0, //左右滚动条位置
              // scrollTop: 0, //上下滚动条位置
              // zoomRatio: 1, // 缩放比例
              // showGridLines: 1, //是否显示网格线
            },
          ],
        }),
      },
    },
    components: { ehlForm },
    data() {
      return {
        confirm: {
          data: {},
          options: {
            first: {
              type: 'label',
              label: '原数据',
              lineStyle: { display: 'inline-block', width: '30%' },
              class: 'cpt_grey_background',
            },
            current: {
              type: 'label',
              label: '现数据',
              lineStyle: { display: 'inline-block', width: '30%' },
              class: 'cpt_grey_background',
            },
            increment: {
              type: 'label',
              label: '增量',
              lineStyle: { display: 'inline-block', width: '30%' },
              class: 'cpt_grey_background',
            },
          },
        },
        valueCopy: {},
      }
    },
    async mounted() {
      this.initCheet()
      this.addImport()
    },
    methods: {
      async initCheet() {
        let that = this
        try {
          importCss('luckysheet/plugins/css/pluginsCss.css')
          importCss('luckysheet/plugins/plugins.css')
          importCss('luckysheet/css/luckysheet.css')
          importCss('luckysheet/assets/iconfont/iconfont.css')
          await importJs('luckysheet/plugins/js/plugin.js')
          await importJs('luckysheet/luckysheet.umd.js')
          this.defaultConfig.allowEdit = !this.readOnly
          this.defaultConfig.data[0].celldata = this.value
          this.defaultConfig.data[0].config = this.config
          this.defaultConfig.hook.cellMousedown = (cell, position, sheet, ctx) => {
            that.updateCopy()
            // console.log(that.valueCopy[`${position.r}_${position.c}`])
            that.confirm.data = that.valueCopy[`${position.r}_${position.c}`] || {}
            return true
          }
          this.defaultConfig.hook.cellUpdateBefore = (r, c, newValue, isRefresh) => {
            if (Number.isNaN(Number(newValue))) {
              $message.error('请输入数字')
              return false
            }
            return true
          }
          this.defaultConfig.hook.cellUpdated = (r, c, oldValue, newValue, isRefresh) => {
            luckysheet.refreshFormula()
            that.updateCopy()
            return true
          }
          this.defaultConfig.hook.rangePullAfter = () => {
            return true
          }
          luckysheet.create(this.defaultConfig)
        } catch (error) {
          console.log(error)
        }
      },
      updateCopy() {
        let that = this
        let arr = this.exportData().value
        arr.forEach(i => {
          let tmp = that.valueCopy[`${i.r}_${i.c}`]
          if (tmp && tmp.first) {
            i.first = tmp.first
            if (tmp.first !== i.v.v) {
              i.v['bg'] = '#f6b26b'
            }
          } else {
            i.first = i.v.v
          }
          i.current = i.v.v
          i.increment = Number(i.current) - Number(i.first)
          that.valueCopy[`${i.r}_${i.c}`] = i
        })
        // console.log(that.valueCopy)
      },
      //导入本地excel后解析
      addImport() {
        let that = this
        this.$refs.selectFile.onchange = evt => {
          var files = evt.target.files
          if (files == null || files.length == 0) {
            alert('No files wait for import')
            return
          }
          let name = files[0].name
          let suffixArr = name.split('.'),
            suffix = suffixArr[suffixArr.length - 1]
          if (suffix != 'xlsx') {
            alert('Currently only supports the import of xlsx files')
            return
          }
          LuckyExcel.transformExcelToLucky(
            files[0],
            function (exportJson, luckysheetfile) {
              if (exportJson.sheets == null || exportJson.sheets.length == 0) {
                alert(
                  'Failed to read the content of the excel file, currently does not support xls files!',
                )
                return
              }
              luckysheet.destroy()
              that.defaultConfig.data = [
                Object.assign(exportJson.sheets[0], { zoomRatio: 1, showGridLines: 0 }),
              ]
              luckysheet.create(that.defaultConfig)
              that.confirm.data = {}
              that.valueCopy = {}
              that.$refs.selectFile.value = ''
            },
          )
        }
      },
      camera() {
        console.log(this.exportData())
      },
      //导出数据
      exportData() {
        // console.log(luckysheet.getLuckysheetfile())
        let arrAll = luckysheet.getLuckysheetfile()[0].data
        let arrLineLength = luckysheet.getLuckysheetfile()[0].data[0].length
        let result = []
        arrAll = arrAll.flat()
        arrAll.forEach((element, index) => {
          if (element) {
            result.push({
              c: index % arrLineLength,
              r: parseInt(index / arrLineLength),
              v: element,
            })
          }
        })
        return { value: result, config: luckysheet.getLuckysheetfile()[0].config }
      },
    },
  }
</script>
